package it.uniroma2.art.coda.imdb;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.pear.tools.PackageBrowser;
import org.apache.uima.pear.tools.PackageInstaller;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.ResourceSpecifier;
import org.apache.uima.util.InvalidXMLException;
import org.apache.uima.util.XMLInputSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestAnnotator {

	static private String[] htmlFilePathArray = { 
		"E:/CODATest/imdb/Interstate 60.htm",
		"E:/CODATest/imdb/Interstate 60 - fullcredits.htm",
		"E:/CODATest/imdb/V per Vendetta.htm",
		"E:/CODATest/imdb/V per Vendetta-fullcredits.htm",
		"E:/CODATest/imdb/buffy.htm",
		"E:/CODATest/imdb/buffy-fullcredits.htm",
	};
	
	private static Logger logger = LoggerFactory.getLogger(TestAnnotator.class);

	public static void main(String[] args) {
		logger.debug("inizio main TestAnnotator");

		TestAnnotator testAnn = new TestAnnotator();

		String pearPathString = "E:\\CODATest\\imdb.pear";
		String installedPearString = "E:\\CODATest\\installedPear";
		try {
			String descrPathString = testAnn.installPear(pearPathString, installedPearString);

			for (int i = 0; i < htmlFilePathArray.length; ++i) {
				logger.info("parsing file = " + htmlFilePathArray[i]); // da cancellare
				String textToBeAnnotatate = testAnn.getTextToBeAnnotated(htmlFilePathArray[i]);

				// use the UIMA AAE to annotate the text
				logger.info("annotating file = " + htmlFilePathArray[i]); // da cancellare
				JCas annotCas = testAnn.analyzeText(descrPathString, textToBeAnnotatate);

			}
			logger.debug("fine main TestAnnotator");

		} catch (IOException e) {
			e.printStackTrace();
		} catch (AnalysisEngineProcessException e) {
			e.printStackTrace();
		} catch (ResourceInitializationException e) {
			e.printStackTrace();
		} catch (InvalidXMLException e) {
			e.printStackTrace();
		}
	}

	public String installPear(String pearPathString, String installedPearString) throws IOException {
		File pearFile = new File(pearPathString);
		File installDir = new File(installedPearString);
		if (installDir.exists()) {
			this.deleteDirectory(installDir);
		}
		PackageBrowser instPear = PackageInstaller.installPackage(installDir, pearFile, true);
		return instPear.getComponentPearDescPath();
	}

	private boolean deleteDirectory(File path) {
		if (path.exists()) {
			File[] files = path.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					files[i].delete();
				}
			}
		}
		return (path.delete());
	}

	private String getTextToBeAnnotated(String htmlFilePath) throws IOException {
		// read the input file containig the test to be analized
		InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(htmlFilePath),
				"UTF-8");
		BufferedReader br = new BufferedReader(inputStreamReader);

		StringBuilder contents = new StringBuilder();
		String line;

		while ((line = br.readLine()) != null) {
			contents.append(line);
			contents.append(System.getProperty("line.separator"));
		}
		return contents.toString();
	}

	private JCas analyzeText(String descrPathString, String textToBeAnnotatate) throws IOException,
			ResourceInitializationException, AnalysisEngineProcessException, InvalidXMLException {
		// pass the txt read to the AE (which is an AAE). To do this read the AAE descriptor and then execute
		// the AAE
		XMLInputSource in;
		ResourceSpecifier specifier;
		AnalysisEngine ae;
		JCas annotCas;

		// in = new XMLInputSource(aggregateAEFilePath);
		in = new XMLInputSource(descrPathString);
		specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
		ae = UIMAFramework.produceAnalysisEngine(specifier);
		ae.setConfigParameterValue("Encoding", "UTF-8");
		annotCas = ae.newJCas();
		annotCas.setDocumentText(textToBeAnnotatate);
		ae.process(annotCas);
		return annotCas;
	}
}
